package lbj.cyw.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lbj.cyw.common.constant.ProductConstant;
import lbj.cyw.common.utils.PageUtils;
import lbj.cyw.common.utils.Query;
import lbj.cyw.gulimall.product.dao.AttrAttrgroupRelationDao;
import lbj.cyw.gulimall.product.dao.AttrGroupDao;
import lbj.cyw.gulimall.product.dao.CategoryDao;
import lbj.cyw.gulimall.product.entity.AttrAttrgroupRelationEntity;
import lbj.cyw.gulimall.product.entity.AttrGroupEntity;
import lbj.cyw.gulimall.product.entity.CategoryEntity;
import lbj.cyw.gulimall.product.service.CategoryService;
import lbj.cyw.gulimall.product.vo.AttrGroupRelationVo;
import lbj.cyw.gulimall.product.vo.AttrRespVo;
import lbj.cyw.gulimall.product.vo.AttrVO;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import lbj.cyw.gulimall.product.dao.AttrDao;
import lbj.cyw.gulimall.product.entity.AttrEntity;
import lbj.cyw.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationDao relationDao;
    @Autowired
    AttrGroupDao attrGroupDao;
    @Autowired
    CategoryDao categoryDao;
    @Autowired
    CategoryService categoryService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVO attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        // 1. 保存基本数据
        this.save(attrEntity);
        System.out.println(attrEntity);
        //2. 保存关联关系
        if(attr.getAttrType()== ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() & attr.getAttrGroupId()!=null){
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            // 属性的id不在传输数据内, 自动增长的
            relationEntity.setAttrId(attrEntity.getAttrId());
//        System.out.println(relationEntity);
            relationDao.insert(relationEntity);
        }


    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String type) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("attr_type",
                "base".equalsIgnoreCase(type)?ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():
                        ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());

        if(catelogId!=0L){
            // 骚操作!
            wrapper.eq("catelog_id",catelogId);
        }
        String key=(String)params.get("key");
        if(!StringUtils.isEmpty(key)){
            // 模糊查询 key可以为catelogId或者name
            wrapper.and((queryWrapper)->{
                queryWrapper.eq("catelog_id",key).or().like("name",key);
            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        // AttrEntity里面并没有所属分类, 和所属分组
        // 利用attrRespVo设置所属分类与所属分组,再进行传递
        // 此操作会涉及多个表
        List<AttrEntity> records = page.getRecords();
        PageUtils pageUtils=new PageUtils(page);
        // 查到属性后还要结合分类名字、分组名字(分类->属性->分组) 封装为AttrRespVo对象
        List<AttrRespVo> respVos = records.stream().map(attrEntity -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);

            if("base".equalsIgnoreCase(type)){
                // 设置分类的分组和名字attrEntity
                AttrAttrgroupRelationEntity attr_id = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));

                if (attr_id != null && attr_id.getAttrGroupId()!=null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attr_id.getAttrGroupId());
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }

            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            return attrRespVo;

        }).collect(Collectors.toList());

        pageUtils.setList(respVos);
        return pageUtils;
    }

    /*属性表, 属性分组表, 属性与属性分组关系表*/
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo attrRespVo = new AttrRespVo();
        AttrEntity byId = this.getById(attrId);
        BeanUtils.copyProperties(byId,attrRespVo);


        if(byId.getAttrType()== ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            // 1. 设置分组信息
            AttrAttrgroupRelationEntity attr_id = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", byId.getAttrId()));
            if(attr_id!=null){
                // 查询分组id,分组名字  ,分组id对于回显没有作用,顺便查了
                attrRespVo.setAttrGroupId(attr_id.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attr_id.getAttrGroupId());
                if(attrGroupEntity!=null){
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }

        //2. 设置分类路径信息
        //此业务只需要查处路径id即可, 有路径id前端就能回显名字
        Long catelogId = byId.getCatelogId();
        Long[] catelogpath = categoryService.findCatelogpath(catelogId);
        attrRespVo.setCatelogPath(catelogpath);
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if(categoryEntity!=null){
            // 名字设不设对此业务没影响
            attrRespVo.setCatelogName(categoryEntity.getName());
        }
        return attrRespVo;
    }

    @Transactional
    @Override
    public void updateAttr(AttrVO attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        // 虽然是通过Id进行修改, 但传入的是一个对象
        this.updateById(attrEntity);


        if(attrEntity.getAttrType()== ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            //修改分组关联
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrId(attr.getAttrId());
            //attr表中没有AttrGroupId, 但是vo中有
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            // 更新整条记录, 要传入修改后的整个实体
            relationDao.update(attrAttrgroupRelationEntity,new UpdateWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id",attr.getAttrId()));

            Integer count = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if(count>0){
                relationDao.update(attrAttrgroupRelationEntity,new UpdateWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_id",attr.getAttrId()));
            }else{
                relationDao.insert(attrAttrgroupRelationEntity);
            }
        }


    }

    // 根据分组Id找到组内所有关联的属性
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> entities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        System.out.println("传入的entities是:"+entities);
        // 传入的entities为空会报错
        //TODO 传入的entities为空会报错,待解决
            List<Long> attrIds = entities.stream().map((attr) -> {
                return attr.getAttrId();
            }).collect(Collectors.toList());
            //  通过一组id获取一个实体集合
            System.out.println("传入的attrIds是:"+attrIds);
            if(attrIds==null || attrIds.size()==0){
                return null;
            }
            Collection<AttrEntity> attrEntitiies = this.listByIds(attrIds);
            return (List<AttrEntity>)attrEntitiies;


    }

    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {
        List<AttrAttrgroupRelationEntity> entities = Arrays.asList(vos).stream().map((item) -> {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, attrAttrgroupRelationEntity);
            return attrAttrgroupRelationEntity;
        }).collect(Collectors.toList());
        relationDao.deleteBatchRelation(entities);
    }

    /*获取当前分组没有关联的属性
    **/
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        //1. 当前分组只能关联自己所属分类里面的属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        //2. 当前分组只能关联别的分组没有引用的属性
        // 2.1 当前分类下的其他分组
        List<AttrGroupEntity> group = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> collect = group.stream().map((item) -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());
        //2.2 这些分组关联的属性
        List<AttrAttrgroupRelationEntity> groupId = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", collect));
        List<Long> attrIds = groupId.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());

        //2.3 从当前分类的属性中移除这些属性
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if(attrIds!=null && attrIds.size()>0){
            wrapper.notIn("attr_id",attrIds);
        }
        // 模糊查询
        String key=(String)params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and(w->{
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        PageUtils pageUtils = new PageUtils(page);

        return pageUtils;
    }

}